<template>
  <van-nav-bar
    :title="id ? '编辑地址' : '新增地址'"
    left-arrow
    @click-left="$router.back()"
  >
    <template #right>
      <van-icon name="ellipsis" />
    </template>
  </van-nav-bar>
  <van-address-edit
    :address-info="info"
    :area-list="areaList"
    :show-delete="id ? true : false"
    show-set-default
    :area-columns-placeholder="['请选择', '请选择', '请选择']"
    @save="onSave"
    @delete="onDelete"
  />
</template>

<script setup>
import { areaList } from "@vant/area-data";
import {
  addAddress,
  getAddressDetail,
  updateAddress,
  removeAddress,
} from "@/api/index.js";
import { showToast } from "vant";
import { useRouter, useRoute } from "vue-router";
import { ref } from "vue";
let router = useRouter();
let route = useRoute();

let info = ref({});

let id = route.query.addressId;
if (id) {
  // 如果id存在，需要根据id获取某个地址的详情
  getDetail();
}

const getAreaCode = (area) => {
  console.log("--areaList:", areaList);
  // 130636: "顺平县"
  area = area.replace(/区|县|市/, "");
  for (let k in areaList.county_list) {
    console.log("--K", k);
    if (areaList.county_list[k].includes(area)) {
      return k;
    }
  }
};

// 获取地址详情
async function getDetail() {
  let { data } = await getAddressDetail(id);
  info.value = {
    id: data.addressId,
    name: data.userName,
    tel: data.userPhone,
    province: data.provinceName,
    city: data.cityName,
    country: data.regionName,
    addressDetail: data.detailAddress,
    areaCode: getAreaCode(data.regionName),
    isDefault: data.defaultFlag ? true : false,
  };
}

let onSave = (obj) => {
  let option = {
    cityName: obj.city,
    defaultFlag: obj.isDefault ? 1 : 0,
    detailAddress: obj.addressDetail,
    provinceName: obj.province,
    regionName: obj.country,
    userName: obj.name,
    userPhone: obj.tel,
    areaCode: obj.areaCode,
    postalCode: "",
  };
  if (id) {
    // 实现编辑
    updateAddress({ ...option, addressId: id }).then((res) => {
      if (res.resultCode === 200) {
        showToast("编辑成功");
        router.push("/addressList");
      }
    });
  } else {
    addAddress({ ...option }).then((res) => {
      if (res.resultCode === 200) {
        showToast("新增成功");
        router.push("/addressList");
      }
    });
  }
};

let onDelete = (item) => {
  removeAddress(item.id).then((res) => {
    if (res.resultCode === 200) {
      showToast("删除成功");
      setTimeout(() => {
        router.back();
      }, 500);
    }
  });
};
</script>

<style lang="scss" scoped>
</style>